package com.artisan.requestbodycache.interceptor;

import com.artisan.requestbodycache.wrapper.CachedHttpServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;

/**
 * 参数校验拦截器
 * 演示：在拦截器中读取 Body 进行校验
 * 优势：即使在拦截器中读取了 Body，Controller 依然可以正常获取
 */
@Component
public class ParamValidationInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(ParamValidationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 仅处理 POST/PUT/PATCH 请求
        String method = request.getMethod();
        if (!"POST".equals(method) && !"PUT".equals(method) && !"PATCH".equals(method)) {
            return true;
        }

        // 关键：在拦截器中读取 Body 进行校验
        if (request instanceof CachedHttpServletRequest) {
            CachedHttpServletRequest cachedRequest = (CachedHttpServletRequest) request;
            byte[] bodyBytes = cachedRequest.getBodyCache();
            
            if (bodyBytes != null && bodyBytes.length > 0) {
                String body = new String(bodyBytes, StandardCharsets.UTF_8);
                
                log.debug("拦截器校验 - URI: {}", request.getRequestURI());
                log.debug("拦截器校验 - Body 长度: {} bytes", bodyBytes.length);
                
                // 示例：检查是否包含敏感词
                if (containsSensitiveWords(body)) {
                    log.warn("⚠️  请求包含敏感词，已拒绝");
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write("{\"error\": \"请求包含敏感词\"}");
                    return false;
                }
                
                // 示例：检查 Body 大小限制（5MB）
                int maxBodySize = 5 * 1024 * 1024;
                if (bodyBytes.length > maxBodySize) {
                    log.warn("⚠️  请求体过大: {} bytes，已拒绝", bodyBytes.length);
                    response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write("{\"error\": \"请求体过大\"}");
                    return false;
                }
                
                log.debug("✅ 参数校验通过");
            }
        } else {
            log.warn("⚠️  请求未被缓存，跳过校验");
        }

        return true;
    }

    /**
     * 检查是否包含敏感词（示例）
     */
    private boolean containsSensitiveWords(String content) {
        // 这里只是示例，实际项目中应该使用更完善的敏感词过滤库
        String[] sensitiveWords = {"hack", "attack", "malware", "敏感词测试"};
        
        String lowerContent = content.toLowerCase();
        for (String word : sensitiveWords) {
            if (lowerContent.contains(word.toLowerCase())) {
                return true;
            }
        }
        
        return false;
    }
}

